﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class ButtonScript : MonoBehaviour {

    public GameObject target;
    public bool clicked;

    private float speed;

    Vector3 touchPosWorld;

    void Start()
    {
        speed = 0.12f;
    }

    void FixedUpdate()
    {
        if (Input.touchCount > 0 && (Input.GetTouch(0).phase == TouchPhase.Began || Input.GetTouch(0).phase == TouchPhase.Moved))
        {
            touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

            if (touchPosWorld.x <= target.transform.position.x)
            {
                target.transform.position = new Vector3(target.transform.position.x - speed, target.transform.position.y, target.transform.position.z);
                target.GetComponent<SpriteRenderer>().flipX = true;
            }

            if (touchPosWorld.x >= target.transform.position.x)
            {
                target.transform.position = new Vector3(target.transform.position.x + speed, target.transform.position.y, target.transform.position.z);
                target.GetComponent<SpriteRenderer>().flipX = false;
            }
        }

        if (clicked && this.gameObject.transform.name == "ButtonLeft")
        {
            target.transform.position = new Vector3(target.transform.position.x - speed, target.transform.position.y, target.transform.position.z);
            target.GetComponent<SpriteRenderer>().flipX = true;
        }

        if (clicked && this.gameObject.transform.name == "ButtonRight")
        {
            target.transform.position = new Vector3(target.transform.position.x + speed, target.transform.position.y, target.transform.position.z);
            target.GetComponent<SpriteRenderer>().flipX = false;
        }
    }

    public void OnMouseOver()
    {
        if(EventSystem.current.IsPointerOverGameObject())
        {
            clicked = true;
        }
    }

    public void OnMouseExit()
    {
        clicked = false;
    }
}
